package com.accounting.client.frontend.order;

import com.accounting.client.ApplicationContext;
import com.accounting.client.frontend.common.CurrencyBox;
import com.accounting.client.frontend.common.CustomerSelector;
import com.accounting.client.remote.Services;
import com.accounting.client.remote.enumeration.Courier;
import com.accounting.client.remote.obj.Customer;
import com.accounting.client.remote.obj.Product;
import com.accounting.client.remote.obj.User;
import com.accounting.client.remote.transfer.CreateQuickOrderRequest;
import com.accounting.client.resource.BoxResources;
import com.accounting.client.session.ErrorHandler;
import com.accounting.client.session.SessionManager;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Widget;

import corelib.client.Util;
import corelib.client.delegate.Action;
import corelib.client.delegate.DataCallback;
import corelib.client.resource.CommonResources;
import corelib.client.search.PagingRequest;
import corelib.client.search.PagingResult;
import corelib.client.ui.widget.Size;
import corelib.client.ui.widget.WidgetListener;
import corelib.client.ui.widget.WindowHandle;
import corelib.client.ui.widget.button.Button;
import corelib.client.ui.widget.button.IsButton;
import corelib.client.ui.widget.dialog.SimpleDialog;
import corelib.client.ui.widget.dialog.SimpleDialogHandler;
import corelib.client.ui.widget.form.DateBox;
import corelib.client.ui.widget.form.DecimalBox;
import corelib.client.ui.widget.form.IntInputBox;
import corelib.client.ui.widget.form.SelectField;
import corelib.client.ui.widget.form.SimpleLabel;
import corelib.client.ui.widget.form.TextAreaField;
import corelib.client.ui.widget.form.TextField;
import corelib.client.ui.widget.form.fomatters.ValueFormatter;
import corelib.client.ui.widget.layout.LabelAlignment;
import corelib.client.ui.widget.layout.RelativeColumn;
import corelib.client.ui.widget.layout.RelativeLayout;

public class CreateQuickOrderHandler extends SimpleDialogHandler {
	
	private Action action;
	private String customerId;
	
	private SelectField<Product> productField;
	private SelectField<User>    operatorField;
	private SelectField<Courier> courierField;
	private SelectField<User>    postOperatorField;
	
	private DecimalBox   purchaseRateField 	= new DecimalBox();
	private DecimalBox   orderRateField    	= new DecimalBox();
	private DecimalBox   postRateField     	= new DecimalBox();
	private CurrencyBox  costField   	    = new CurrencyBox();
	private IntInputBox  countField 	    = new IntInputBox();
	private CurrencyBox  priceField 	    = new CurrencyBox();
	private CurrencyBox  postageField       = new CurrencyBox();
	private TextField trackingIdField    = new TextField();
	private TextField recipientField     = new TextField();
	private TextField phoneNumberField   = new TextField();
	private TextAreaField  addressField       = new TextAreaField();
	private DateBox      datePurchasedField = new DateBox();
	private DateBox 	 datePostedField    = new DateBox();
	
	public CreateQuickOrderHandler(Action action){
		this.action = action;
	}
	
	public String getCustomerId() {
		return this.customerId;
	}

	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}

	@Override
	public String getHeading() {
		return "快捷创建销售记录";
	}

	@Override
	public Size getSize() {
		return new Size(700, 700);
	}

	@Override
	public Widget getContentPanel() {
		productField = new SelectField<Product>(new ValueFormatter<Product>(){
			@Override
			public String format(Product value) {
				if (value == null){
					return "请选择产品";
				}
				return value.getCName();
			}
		},true);
		
		operatorField = new SelectField<User>(ApplicationContext.getAllUsers(),new ValueFormatter<User>(){
			@Override
			public String format(User value) {
				if (value == null){
					return "请选择操作员";
				}
				return value.getCName();
			}
		},true);
		
		postOperatorField = new SelectField<User>(ApplicationContext.getAllUsers(),new ValueFormatter<User>(){
			@Override
			public String format(User value) {
				if (value == null){
					return "请选择操作员";
				}
				return value.getCName();
			}
		},true);
		
		courierField = new SelectField<Courier>(Courier.All, new ValueFormatter<Courier>(){
			@Override
			public String format(Courier value) {
				if (value == null){
					return "请选择快递公司";
				}
				return value.getCName();
			}
		},true);
		
		int fw 	  = 150;
		int lw 	  = 100;
		int space = 8;
		
		ScrollPanel scrolPanel = new ScrollPanel();
		RelativeLayout layout = RelativeLayout.create(fw,LabelAlignment.Top, lw);
		
		RelativeColumn column  = new RelativeColumn();
		column.setRowSpacing(5);
		column.getPanel().getElement().getStyle().setPadding(20, Unit.PX);
		
		column.addRow().add(new SimpleLabel("汇率信息").setBold(true),300);
		
		column.addRow()
			  .addSpace(space)
			  .add(new SimpleLabel("购买时汇率"), purchaseRateField, layout)
			  .addSpace(space)
			  .add(new SimpleLabel("销售时汇率"), orderRateField, layout)
			  .addSpace(space)
			  .add(new SimpleLabel("邮寄时汇率"), postRateField, layout);
		
		column.addRow().add(new SimpleLabel("购买销售记录").setBold(true), 300);
		
		column.addRow()
			  .addSpace(space)
			  .add(new SimpleLabel("选择产品"), productField, layout)
			  .addSpace(space)
			  .add(new SimpleLabel("产品单价"), costField,    layout)
			  .addSpace(space)
			  .add(new SimpleLabel("购买员"),  operatorField, layout)
			  .addSpace(space)
			  .add(new SimpleLabel("购买时间"), datePurchasedField, layout);
		
		column.addRow()
			  .addSpace(space)
			  .add(new SimpleLabel("销售单价"), priceField, layout)
			  .addSpace(space)
			  .add(new SimpleLabel("数量"), countField, layout)
			  ;
		
		column.addRow().add(new SimpleLabel("快递信息").setBold(true), 300);
		
		column.addRow()
			  .addSpace(space)
			  .add(new SimpleLabel("选择快递"), courierField, layout)
			  .addSpace(space)
			  .add(new SimpleLabel("快递单号"),   trackingIdField,layout)
			  .addSpace(space)
			  .add(new SimpleLabel("邮寄员"),  postOperatorField, layout)
			  .addSpace(space)
			  .add(new SimpleLabel("邮寄日期"), datePostedField, layout)
			  ;
		
		column.addRow()
			  .addSpace(space)
			  .add(new SimpleLabel("邮费"), postageField, layout)
			  .addSpace(space)
			  .add(new SimpleLabel(Util.EMPTY_STRING), new Button("选择客户", new WidgetListener(){
				@Override
				public void valueUpdated(Widget widget) {
					SimpleDialog.show(new CustomerSelector(new DataCallback<Customer>() {
						@Override
						public void onCompleted(Customer customerInfo) {
							if (customerInfo != null) {
								syncCustomer(customerInfo);
							}
						}
					}));
				}
			  }), layout);
		
		column.addRow()
			  .addSpace(space)
			  .add(new SimpleLabel("收件人"), recipientField, layout)
			  .addSpace(space)
			  .add(new SimpleLabel("收件人电话号码"), phoneNumberField, layout)
			  ;
		
		addressField.setHeight(150);
		column.addRow()
			  .addSpace(space)
			  .add(new SimpleLabel("收件人地址"), addressField, RelativeLayout.create(500, LabelAlignment.Top, 100))
			  ;
		
		scrolPanel.add(column.getPanel());
		return scrolPanel;
	}

	@Override
	public IsButton[] getButtons() {
		return new IsButton[]{
			new IsButton("确定", CommonResources.INSTANCE.accept16(),100, new WidgetListener(){
				@Override
				public void valueUpdated(Widget widget) {
					createOrder();
				}
			}),
			new IsButton("关闭", BoxResources.INSTANCE.cancel16(),100, new WidgetListener(){
				@Override
				public void valueUpdated(Widget widget) {
					closeDialog();
				}
			})
		};
	}
	
	@Override
	public boolean isCloseable() {
		return false;
	}

	@Override
	public void onClosing(WindowHandle windowHandle) {
		windowHandle.close();
	} 
	
	@Override
	public void onShowing() {
		super.onShowing();
		PagingRequest request = new PagingRequest();
		request.setOffset(0);
		request.setLimit(1000);
		
		Services.ProductService.ListProductsByKeyword(SessionManager.getPassport(), request,
			new AsyncCallback<PagingResult<Product>>(){
				@Override
				public void onFailure(Throwable caught) {
					ErrorHandler.handleServiceError(caught);
				}
				
				@Override
				public void onSuccess(PagingResult<Product> result) {
					productField.setOptions(result.getData());
				}
			}
		);
	}
	
	private void syncCustomer(Customer customerInfo){
		setCustomerId(customerInfo.getId());
		recipientField.setText(customerInfo.getCName());
		phoneNumberField.setText(customerInfo.getPhoneNumber1());
		addressField.setValue(customerInfo.getAddress1());
	}
	
	private boolean validate() {
		if (purchaseRateField.getDouble(0.0) == 0) {
			purchaseRateField.markError("请输入购买时汇率");
			return false;
		}
		if (orderRateField.getDouble(0.0) == 0) {
			orderRateField.markError("请输入下单时汇率");
			return false;
		}
		if (postRateField.getDouble(0.0) == 0){
			postRateField.markError("请输入邮寄时汇率");
			return false;
		}
		if (productField.getSelectedOption() == null){
			productField.markError("请选择产品");
			return false;
		}
		if (costField.getDouble(0.0) == 0){
			costField.markError("请输入购买时单价");
			return false;
		}
		if (operatorField.getSelectedOption() == null){
			operatorField.markError("请选择购买操作员");
			return false;
		}
		if (datePurchasedField.getDate() == null){
			datePurchasedField.markError("请输入购买日期");
			return false;
		}
		if (priceField.getDouble(0.0) == 0){
			priceField.markError("请输入销售单价");
			return false;
		}
		if (countField.getInteger(0) == 0){
			countField.markError("请输入销售数量");
			return false;
		}
		if (courierField.getSelectedOption() == null){
			courierField.markError("请输入快递公司");
			return false;
		}
		if (Util.isNullOrEmpty(trackingIdField.getText())){
			trackingIdField.markError("请输入订单号");
			return false;
		}
		if (postOperatorField.getSelectedOption() == null){
			postOperatorField.markError("请输入邮寄操作员");
			return false;
		}
		if (postageField.getDouble(0.0) == 0){
			postageField.markError("请输入单件邮费");
			return false;
		}
		if (Util.isNullOrEmpty(getCustomerId())){
			recipientField.markError("请选择收件人");
			return false;
		}
		if (Util.isNullOrEmpty(phoneNumberField.getText())){
			phoneNumberField.markError("请输入收件人电话号码");
			return false;
		}
		if (Util.isNullOrEmpty(addressField.getValue())){
			addressField.markError("请输入订单号");
			return false;
		}
		return true;
	}
	
	private void createOrder() {
		if (validate() == Boolean.FALSE){
			return;
		}
		
		CreateQuickOrderRequest request = new CreateQuickOrderRequest();
		
		request.setTrackingId(trackingIdField.getText());
		request.setAddress(addressField.getTrimmedValueOrEmptyString());
		request.setCourierId(courierField.getSelectedOption().getCode());
		request.setCost(costField.getDouble());
		request.setCount(countField.getInteger());
		
		request.setCustomerId(getCustomerId());
		request.setDatePurchased(datePurchasedField.getDate());
		request.setOperatorId(operatorField.getSelectedOption().getUserId());
		
		request.setOrderCurrencyRate(orderRateField.getDouble());
		request.setPhoneNumber(phoneNumberField.getText());
		request.setPostage(postageField.getDouble());
		
		request.setPostCurrencyRate(postRateField.getDouble());
		request.setPostOperatorId(postOperatorField.getSelectedOption().getUserId());
		request.setPrice(priceField.getDouble());
		request.setProductId(productField.getSelectedOption().getProductId());
		request.setPurchaseCurrencyRate(purchaseRateField.getDouble());
		
		String passport = SessionManager.getPassport();
		Services.OrderService.CreateQuickOrder(passport, request, new AsyncCallback<Boolean>(){
			@Override
			public void onFailure(Throwable caught) {
				ErrorHandler.handleServiceError(caught);
			}

			@Override
			public void onSuccess(Boolean result) {
				if (result == Boolean.TRUE){
					closeDialog();
					action.run();
				}
			}
		});
	}
}
